#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>

int main()
{
	/*umask(0);
	//int fd = open("log.txt", O_CREAT | O_WRONLY | O_TRUNC, 0666);
	int fd = open("log.txt", O_CREAT | O_WRONLY | O_APPEND, 0666);
	if(fd < 0)
	{
		perror("open");
		return 1;
	}

	printf("fd:%d\n", fd);
	
	//const char* msg = "hello\n";
	int cnt = 1;
	int a = 1234567;
	while(cnt)
	{
		//当字符来写
		char buffer[16];
		snprintf(buffer, sizeof(buffer), "%d", a);
		write(fd, buffer, strlen(buffer));
		cnt--;
	}

	close(fd);*/
	//close(1);
	//int fd = open("log.txt", O_CREAT | O_WRONLY | O_TRUNC, 0666);
	//printf("fd: %d\n",fd);
	//close(fd);

	//int fd = open("log.txt", O_CREAT |  O_WRONLY | O_TRUNC, 0666);
	//if(fd < 0) exit(1);
	//dup2(fd, 1);
	//close(fd);
	
	//close(1);
	//fd == 1
	//int fd = open("log.txt", O_CREAT | O_WRONLY | O_TRUNC, 0666);
	//默认向显示器打印
	//库函数
	//printf("fd: %d\n",fd);
	//printf("hello\n");
	//printf("hello\n");
	//printf("hello\n");
	//系统调用
	//const char* msg = "hello write\n";
	//write(fd, msg, strlen(msg));
	//close(fd);
    FILE *fp = fopen("./bite", "wb+");
    if (fp == NULL)
	{
        perror("fopen error");
        return -1; 
    }   
    fseek(fp, 0, SEEK_SET);
    char *data = "linux so easy!\n";
    //size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
    size_t ret = fwrite(data, 1, strlen(data), fp);
    if (ret != strlen(data))
	{
        perror("fwrite error");
        return -1; 
    }   
    fseek(fp, 0, SEEK_SET);//跳转读写位置到，从文件起始位置开始偏移0个字节
    char buf[1024] = {0};
    //size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
    ret = fread(buf, 1, 1023, fp);//因为设置读取块大小位1，块个数为1023因此fread返回值为实际读取到的数据长度
    if (ret == 0)
	{
        if (ferror(fp)) //判断上一次IO操作是否正确
            printf("fread error\n");
        if (feof(fp)) //判断是否读取到了文件末尾
            printf("read end of file!\n");
        return -1; 
    }   
    printf("%s", buf);
    fclose(fp);
    return 0;
}
